import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))

import json
import requests
from reqapi.api import BaseApi
import logging

class GetCommodityTrendApi(BaseApi):
    """获取商品历史交易数据API"""
    
    def __init__(self, device_id, device_token, auth_token, uk):
        super().__init__(device_id, device_token, auth_token, uk)
        

    

    def execute(self, template_id, day=7, order_type=1):
        """
        执行API请求获取商品历史交易数据
        
        Args:
            template_id: 商品模板ID
            day: 查询天数，默认7天
            order_type: 订单类型，默认1
            
        Returns:
            dict: API响应数据
        """
        url = f"{self.BASE_URL}/api/youpin/price/trend/data"
        
        # 请求数据
        data = {
            "orderType": order_type,
            "day": day,
            "templateId": template_id
        }
        headers = self.common_headers.copy()
        print("\n=== 请求信息 ===")
        print(f"请求URL: {url}")
        print(f"请求方法: POST")
        print(f"请求头: {json.dumps(headers, indent=2, ensure_ascii=False)}")
        print(f"请求数据: {json.dumps(data, indent=2, ensure_ascii=False)}")
        try:
            response = self.interceptor.send_request(url, json=data, headers=headers, need_encrypt=False)
            print("\n=== 响应信息 ===")
            if isinstance(response, dict):
                result = response
            elif hasattr(response, 'json'):
                result = response.json()
            else:
                result = response
            print(f"响应数据: {json.dumps(result, indent=2, ensure_ascii=False)}")
            if result.get('code') != 0:
                print(f"API返回错误: {result.get('msg', '未知错误')}")
                return None
            data = result.get('data', {})
            trade_data = {
                'trade_list': data.get('tradeDataList', []),
                'price_range': data.get('tradePriceList', []),
                'block_num': data.get('blockNum', 0)
            }
            return trade_data
        except Exception as e:
            print(f"请求发生错误: {str(e)}")
            return None
